# Create your views here.
from django.http import HttpResponse
from django.shortcuts import render
from django.conf import settings
from django.http import JsonResponse
import pandas as pd


def index(request):
    return render(request, 'index.html', context={})


# 1-12月份销售和利润数据
def bar_data(request):           # 使用Django提供的settings.BASE_DIR作为绝对路径来读取本地文件
    # 读取CSV文件
    data = pd.read_csv(f'{settings.BASE_DIR}/static/data/sample_data.csv', encoding='gbk')

    # 将日期列转换为日期类型
    data['日期'] = pd.to_datetime(data['日期'])

    # 按月份进行分组，并计算销售额和利润总和
    monthly_data = data.groupby(data['日期'].dt.month)[['销售额', '利润']].sum()

    # 获取销售额和利润的列表
    sales = monthly_data['销售额'].tolist()
    profit = monthly_data['利润'].tolist()

    # 获取月份的列表
    month = monthly_data.index.tolist()
    data = {'month': month, 'sales': sales, 'profit': profit}
    return JsonResponse(data, json_dumps_params={'indent': 4})


# 各个省份销售和利润情况
def map_data(request):
    data = pd.read_csv(f'{settings.BASE_DIR}/static/data/sample_data.csv', encoding='gbk')

    # 按省份进行分组，并计算销售额和利润总和
    province_data = data.groupby(data['省份'])[['销售额', '利润']].sum()
    new_column = province_data['销售额'].copy().rename('value')

    # 将新列添加到DataFrame中，并提到第一位
    province_data.insert(0, 'value', new_column)

    # 将索引变为一列数据
    province_data.reset_index(inplace=True)

    # 重命名列名
    province_data.rename(columns={'省份': 'name'}, inplace=True)
    province_data.rename(columns={'销售额': 'sales'}, inplace=True)
    province_data.rename(columns={'利润': 'profit'}, inplace=True)

    # 将dataframe转换为字典
    province = province_data.to_dict("records")
    data = {'province': province}
    return JsonResponse(data, json_dumps_params={'indent': 4})


# 各个产品和单品销售情况
def sun_data(request):
    df = pd.read_csv(f'{settings.BASE_DIR}/static/data/sample_data.csv', encoding='gbk')
    # 按照类别和产品进行分组，并计算销售额总和
    grouped = df.groupby(['类别', '产品'])['销售额'].sum().reset_index()

    # 构建JSON数据
    data = []
    categories = grouped['类别'].unique()
    for category in categories:
        category_data = {}
        category_data['name'] = category
        category_data['value'] = round(grouped[grouped['类别'] == category]['销售额'].sum(), 2)
        children = []
        products = grouped[grouped['类别'] == category]
        for _, row in products.iterrows():
            product_data = {}
            product_data['name'] = row['产品']
            product_data['value'] = round(row['销售额'], 2)
            children.append(product_data)
        category_data['children'] = children
        data.append(category_data)

    detail = {'detail': data}
    return JsonResponse(detail, json_dumps_params={'indent': 4})


# 各个地区销售和利润情况
def line_data(request):           # 使用Django提供的settings.BASE_DIR作为绝对路径来读取本地文件
    df = pd.read_csv(f'{settings.BASE_DIR}/static/data/sample_data.csv', encoding='gbk')
    province_region = {
        '中南': ['湖北', '湖南', '广东', '海南', '广西', '江西', '河南'],
        '西南': ['四川', '贵州', '云南', '重庆', '西藏'],
        '西北': ['陕西', '甘肃', '青海', '宁夏', '新疆'],
        '华东': ['江苏', '浙江', '安徽', '福建', '上海', '山东'],
        '华北': ['北京', '天津', '河北', '山西', '内蒙古'],
        '东北': ['辽宁', '吉林', '黑龙江'],
        '其他': ['台湾', '香港', '澳门', '南海诸岛']
    }
    # 根据各个省份地理位置进行分组赋值
    df['地区'] = df['省份'].map(
        {province: region for region, provinces in province_region.items() for province in provinces})

    # 按地区求和
    data = df.groupby(['地区'])[['销售额', '利润']].sum()

    # 四舍五入
    data = data.round({'销售额': 0, '利润': 0})

    # 数据转换为列表
    region = data.index.tolist()
    sales = data['销售额'].values.tolist()
    profit = data['利润'].values.tolist()
    data = {'region': region, 'sales': sales, 'profit': profit}
    return JsonResponse(data, json_dumps_params={'indent': 4})


def ld_data(request):           # 使用Django提供的settings.BASE_DIR作为绝对路径来读取本地文件
    df = pd.read_csv(f'{settings.BASE_DIR}/static/data/sample_data.csv', encoding='gbk')
    data = df.groupby(['销售员'])[['销售额', '利润']].sum()

    # 索引改为列数据
    data.reset_index(inplace=True)

    # 将dataframe数据转为字典,格式为{'name': '销售员', 'value': 值}
    sales_dict = [{'name': row['销售员'], 'value': row['销售额']} for index, row in data.iterrows()]
    profit_dict = [{'name': row['销售员'], 'value': row['利润']} for index, row in data.iterrows()]

    # 四舍五入
    rounded_sales_dict = [{'name': d['name'], 'value': round(d['value'], 2)} for d in sales_dict]
    rounded_profit_dict = [{'name': d['name'], 'value': round(d['value'], 2)} for d in profit_dict]

    # 从大到小排序
    sorted_sales_dict = sorted(rounded_sales_dict, key=lambda x: x['value'], reverse=True)
    sorted_profit_dict = sorted(rounded_profit_dict, key=lambda x: x['value'], reverse=True)

    # 取数值前八
    top_8_sales_dict = sorted_sales_dict[:8]
    top_8_profit_dict = sorted_profit_dict[:8]
    data = {'sales': top_8_sales_dict, 'profit': top_8_profit_dict}
    return JsonResponse(data, json_dumps_params={'indent': 4})